package com.yzy.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.yzy.entity.Student;
import com.yzy.service.IStudentService;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author 杨子宇
 */
@Component
public class StuTokenUtils {
    private static IStudentService staticStudentService;

    @Resource
    private IStudentService studentService;

    @PostConstruct
    public void setTeacherService() {
        staticStudentService = studentService;
    }

    /**
     * 获取token
     */
    public static String getToken(Student student) {
        String id = student.getId().toString();
        String username = student.getUsername();

        return JWT.create().withAudience(id)
                // 设置 24 小时后Token过期
                .withExpiresAt(DateUtil.offsetHour(new Date(), 24))
                // 将学生用户名作为Token秘钥
                .sign(Algorithm.HMAC256(username));
    }

    /**
     * 获取当前登录的教师信息
     */
    public static Student getCurrentStudent() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("Tea-token");
            if (StrUtil.isNotBlank(token)) {
                String teacherId = JWT.decode(token).getAudience().get(0);
                return staticStudentService.getById(Integer.valueOf(teacherId));
            }
        } catch (Exception e) {
            return null;
        }

        return null;
    }
}
